﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reactive;
using System.Reactive.Linq;

namespace Atha.Clients.ViewModels
{
	public static class ObservableExtensions
	{
		public static IEnumerable<IObservable<EventPattern<ViewModelEventArgs<TViewModel>>>> FromEventPattern<TViewModel>(
			this IEnumerable<TViewModel> viewModels,
			Expression<Func<TViewModel, EventHandler<ViewModelEventArgs<TViewModel>>>> eventExpression)
			where TViewModel : ViewModelBase
		{
			var memberExpression = eventExpression.Body as MemberExpression;
			var eventName = memberExpression.Member.Name;

			var observables = new List<IObservable<EventPattern<ViewModelEventArgs<TViewModel>>>>();

			foreach (var target in viewModels)
			{
				var observable = Observable.FromEventPattern<ViewModelEventArgs<TViewModel>>(target, eventName);

				observables.Add(observable);
			}

			return observables;
		}
	}
}